<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>[${examination.title}]考试</title>
<%@include file="../core/head.jsp"%>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<link rel="stylesheet" href="${ctx }/css/core.css" type="text/css">
<link rel="stylesheet" href="${ctx }/css/exam.css" type="text/css">
<link rel="stylesheet" href="${ctx }/css/buttons.css" type="text/css">
<script type="text/javascript" src="${ctx }/js/FusionCharts.js"></script>
<script type="text/javascript" src="${ctx }/js/modules/exam/exam.js"></script>
<script type="text/javascript" src="${ctx}/js/modules/code/AjaxAuthFilter.js"></script>
<script type="text/javascript" src="${ctx}/js/modules/code/MessageBox.js"></script>

<link rel="stylesheet" href="${ctx}/js/jquery-ui-1.10.3/css/ui-lightness/jquery-ui-1.10.3.custom.css" type="text/css">
<script type="text/javascript" src="${ctx }/js/jquery-ui-1.10.3/js/jquery-ui-1.10.3.custom.js"></script>
<script type="text/javascript">
var Sidebar = {
		allCount:	0,
		loadCount:0,
		preCount:0,
		wrong : 0,
		correct : 0,
		outlineCount:0,
		canSubmit:false,
		init:function(){
			this.allCount=${examination.questionCount },
			this.loadCount=0,
			this.wrong = parseInt("${examination.wrongCount}"),
			this.correct =parseInt("${examination.correntCount}");
			this.preCount = this.wrong+this.correct;
			this.flashLoadProcess();
			this.flashDoneProcess();
		},
		addOutlineCount:function(){
			this.outlineCount++;
			$("#offlineNum").text("离线：" +this.outlineCount);
		},
		subOutlineCount:function(){
			if(--this.outlineCount==0){
				$("#offlineNum").text("");				
			}else{
			$("#offlineNum").text("离线：" +this.outlineCount);
				
			}
		},
		addLoadCount:function(){
			this.loadCount++;
			this.flashLoadProcess();
		},
		addCorrectCount:function ( ){
			$("#correct").text(++this.correct);
			this.flashDoneProcess();
		},
		addWrongCount:function ( ){
			$("#wrong").text(++this.wrong);
			this.flashDoneProcess();
		},
		
		flashLoadProcess:function( ){
			var value = (this.preCount+this.loadCount)*100/this.allCount;
			$("#load").css("width",value+"%");
		},
		flashDoneProcess:function( ){
			var value = (this.wrong+this.correct)*100/this.allCount;
			$("#done").css("width",value+"%");
		},
		hideLoadButton:function(){
			$("#loadQuestionBut").hide();
		},
		showSubmitExamButton:function(){
			if(!this.canSubmit){
				this.canSubmit = true;	
				$("#submitExamButton").show();
			}
		}
	 
	};
	 


	var Template = {
		tempForm : "试题框架模板",
		tempSummary : "内容模板",
		tempOption : "选项模板",
		tempAnswer : "分析模板",
		init : function() {
			this.tempForm = getHtml("#tempForm");
			this.tempSummary = getHtml("#tempSummary");
			this.tempOption = getHtml("#tempOption");
			this.tempAnswer = getHtml("#tempAnswer");
			function getHtml(id) {
				var obj = $(id);
				var html = obj.html();
				obj.remove();
				return html;
			}

		},
		newInstrance : function(question) {
			var form = $(this.fillValue(this.tempForm, question));
			var oths = {
				"index" : question.index
			};
			for (i in question.accessorys) {
				var accquestion = question.accessorys[i];
				var accsummary = this.fillSummary(accquestion, oths);
				form.find(".summaryArea").append(accsummary);
			}
			var cnsummary = this.fillSummary(question, oths);
			form.find(".summaryArea").append(cnsummary);

			return form;
		},
		fillSummary : function(quest, oths) {
			var sutext = this.fillValue(this.tempSummary, quest, oths);
			var summary = $(sutext);
			var ops = quest.options;
			for (j in ops) {
				var op = ops[j];
				var option = $(this.fillValue(this.tempOption, op));
				summary.find(".optionsArea").append(option);
			}
			return summary;
		},
		fillAnallysis : function(form, question) {
			var analysis = this.fillValue(this.tempAnswer, question);
			var area = form.find(".analysisArea");
			area.html(analysis);
			return area;
		},

		fillValue : function(temp, values, oths) {
			return temp.replace(/\{\s*([^\}]*)\s*\}/g, function(word) {
				var key = word.replace(/^\{\s*|\s*\}$/g, "");
				var val = values[key];
				if (!val && oths) {
					val = oths[key];
				}
				return val;

			});
		}
	};

	var Memory = {
		lastIndex:parseInt("${examination.correntCount+examination.wrongCount}"),
		allQuestons : {},
		online : true,
		outlineAnswers : [],
		activeNum:0,
		minActiveNum:1,
		loadSize:100,
		isLoading:false,
		loadComplate :false,
		setVisible:function(id,boo){
			var question = this.getQuestion(id);
			question.visible= boo;
		},
		hasMoreQuestions:function(){
			return !this.loadComplate;
		},
		setLoadComplate:function(){
			this.loadComplate = true;
		},
		getLoadSize:function(){
			return this.loadSize;
		},
		isOnline : function() {
			return this.online;
		},

		setOnline : function(boo) {
			if (boo != this.online) {
				this.online = boo;
				if (this.online) {
					$.MessageBox.info("转入在线模式");
				} else {
					$.MessageBox.info("转入离线模式");
				}
			}
		},
		setLoadingState:function(boo){
			this.isLoading = true;
		},
		needLoadNew :function(){
			return this.hasMoreQuestions()&&this.activeNum<=this.minActiveNum;
		},
		loadQuestion : function(item) {
			var id = item.id;
			var question = this.getQuestion(id);
			if(!question){
				question = item;
				question.state = 1;
				question.index =  (++this.lastIndex);
				question.visible = false;
				this.allQuestons[id] = question;
				this.activeNum++;
			}
			return question;
		},
		
		doneQuestion : function(id,answer) {
			var question = this.allQuestons[id];
			var iscorrect = false;
			if(question){
				this.activeNum--;
				question.userAnswer = answer;
				question.state = 0;
			    iscorrect =question.userAnswer == question.answer;
			}
			return iscorrect;
			 
		},
		isAllDone:function(){
			return this.loadComplate&& this.activeNum <=0;
		},
		hasOutlineAnswer:function(){
			return this.outlineAnswers.length>0;
		},
		getOutlineAnswerSize:function(){
			return this.outlineAnswers.length;
		},
		addOutlineAnswer : function(answer) {
			this.outlineAnswers.push(answer);
		},
		getOutlineAnswer:function(){
			return this.outlineAnswers.pop();
			
		},
		getQuestion : function(id) {
			
			return this.allQuestons[id];
		},
		getSubmitObject:function(id,state){
			var question = this.getQuestion(id);
			var obj =  {
					"answer.questionId" : id,
					"answer.examId" : "${examination.id}",
					"answer.userAnswer" : question.userAnswer,
					"answer.corrAnswer" : question.answer,
					"answer.state" : state
				};
			return obj;
		},
		getActiveQids : function() {
			var ids = undefined;
			for ( var id in this.allQuestons) {
				var question = this.getQuestion(id);
				if (question.state==1) {
					if (ids == undefined) {
						ids = id;
					} else {
						ids = ids + "," + id;
					}
				}
			}
			return ids;
		}

	};
	
	
	
	

	function loadRemainingQuestions(length,callback) {
		 
		Memory.setLoadingState(true);
		length =isNaN(length)||length<=0? Memory.getLoadSize():length;
		var out = Memory.getActiveQids();
		$.ajax({
			dataType : "json",
			cache : true,
			type : "POST",
			url : "${ctx}/exam/loadRemainingQuestions.action",
			data : {
				"examination.id" : "${examination.id}",
				"examination.forWrong" : "${examination.forWrong}",
				"out" : out,
				"length" : length
			},
			error : function(request) {
				Memory.setOnline(false);
				Memory.setLoadingState(false);
			},
			success : function(data) {
				Memory.setOnline(true);
				if(data == "LOADCOMPLATE"||data.length<length){
					Memory.setLoadComplate();
					Sidebar.hideLoadButton();
				};
				
				var pass = $.AjaxAuthFilter.checkSession("${ctx}/user/ajaxLogin.action", data, function(user) {
					ajaxRecord(answerObject);
				});

				if (pass) {
					for(var i = 0;i<data.length;i++){
						var item = data[i];
						var question = Memory.loadQuestion(item);
						if(!question.visible){
							var context = $("#context");
							var form = Template.newInstrance(question);
							context.append(form);
							question.visible=true;
							Sidebar.addLoadCount();
							 
						}
					};
				}
				Memory.setLoadingState(false);
				if (callback) {
					if (callback.loaded) {
						callback.loaded();
					}
					if (Memory.hasMoreQuestions()) {

						if (callback.hasMore) {
							callback.hasMore();
						}
					} else {
						if (callback.noMore) {
							callback.noMore();
						}
					}

				}

			}
		});
	}
	function loadAllRemainingQuestions() {
		if (Memory.hasMoreQuestions()) {
			loadRemainingQuestions(500, {
				hasMore : function() {
					loadAllRemainingQuestions();
				},
				noMore : function() {
					$.MessageBox.info("全部加载完成");
				}
			}

			);
		}

	}

	function submitAnswer(zhis, qid) {

		var form = $(zhis).parents(".question");
		var userOption = form.find("li:first .option input:checked");

		var userAnswer = userOption.attr("title");
		if (userOption.size() <= 0) {
			$.MessageBox.info("请选择一个答案");
		} else {
			form.find(".option input:radio").attr("disabled", "disabled");
			var question = Memory.getQuestion(qid);
			var anallysis = Template.fillAnallysis(form, question);
			anallysis.slideDown();
			var hideButton = form.find(".hideButton");
			var iscorrect = Memory.doneQuestion(qid, userAnswer);

			if (iscorrect) {
				form.removeClass("wrong");
				Sidebar.addCorrectCount();
				if ($("#autoRemove").get(0).checked == true) {
					form.hide();
				} else {
					hideButton.show();
				}
			} else {
				form.addClass("wrong");
				Sidebar.addWrongCount();
				hideButton.show();
			}

			var state = form.find(".unsure :checked").size();
			var answerObject = Memory.getSubmitObject(qid, state);
			ajaxRecord(answerObject,submitOutlineAnswer );
			form.find(".unsure").hide();
			$(zhis).hide();
			if (Memory.needLoadNew()) {
				loadRemainingQuestions();
			}

		}

	}

	function ajaxRecord(answerObject,callback) {
		$.ajax({
			cache : true,
			type : "POST",
			url : "${ctx}/exam/submitAnswer.action",
			data : answerObject,
			error : function(request) {
				Memory.setOnline(false);
				Memory.addOutlineAnswer(answerObject);
				Sidebar.addOutlineCount();
				showSubmitExamButton();
			},
			success : function(data) {
				Memory.setOnline(true);
				var pass = $.AjaxAuthFilter.checkSession("${ctx}/user/ajaxLogin.action", data, function(user) {
					ajaxRecord(answerObject);
				});
				if (pass) {
					if(callback){
						callback();
					}
				}else{
					Memory.addOutlineAnswer(answerObject);
					Sidebar.addOutlineCount();
				}
				showSubmitExamButton();
			}
		});
		
		
		function showSubmitExamButton(){
			if(Memory.isAllDone()){
				Sidebar.showSubmitExamButton();
				showSubmitDialog();
			}
		}

	}

	
	function submitOutlineAnswer(){
		
		if (Memory.isOnline()&&Memory.hasOutlineAnswer()) {
			$.console("submit outline answer...")
			var answer = Memory.getOutlineAnswer();
			Sidebar.subOutlineCount();
			ajaxRecord(answer,submitOutlineAnswer);
		}else{
			$.console("not outline answer...")
		}
	}
	
	
	function showSubmitDialog(){
		$("#submitPanel").dialog("open");
		
	}
	
	
	
	function removeQuestion(zhis, id) {
		$(zhis).parents(".question").remove();
		Memory.setVisible(id, false);
	}

	function showScore() {
		$("#chart").show();
		var dataxml = "<chart pieYScale='30' decimals='1'  showLabels='1' useRoundEdges='1' formatNumberScale='0' baseFont='宋体' " + "showValues='1' caption='考试成绩" + score.getScore() + "' pieSliceDepth='20' baseFontSize='12'    toolTipSepChar=' ' >"
				+ "<set label='正确' value='"+score.correct+"'  />" + "<set label='错误' value='"+score.wrong+"' /></chart>";

		var myChart = new FusionCharts("${ctx}/charts/Pie3D.swf", "myChartId", "500", 200);
		myChart.setDataXML(dataxml);
		myChart.render("chartdiv");

	}
	
	function loadMore(){
		$.MessageBox.info("加载中...",{delay:-1});
		loadRemainingQuestions(0, {
			hasMore : function() {
				$.MessageBox.info("加载完成");
			},
			noMore : function() {
				$.MessageBox.info("全部加载完成");
			}
		}

		);
		
	}
	 

	$(function() {
		$.MessageBox.info("试题加载中...",{delay: -1});
		Template.init();
		Sidebar.init();
		$.AjaxAuthFilter.init("${user.id}",{logined:updateUser,diff:function(user){
			$.MessageBox.info("登录用户不同，请重新选择试卷！",{callback:function(){
				window.location.href="${ctx}/exam/startExam.action";
			}});
			
		}});
		
		
		loadRemainingQuestions(0, {
			loaded : function() {
				$.MessageBox.info("加载完成");
			}
		});

		
		
		
		$("#submitPanel").dialog({
			autoOpen : false,
			modal : true,
			show : {
				effect : "blind",
				duration : 1000
			},
			hide : {
				effect : "explode",
				duration : 1000
			},
			buttons : {
				"确定" : function() {
					var form = $("#subExamForm");
					if (Memory.isOnline()) {
						if (Memory.hasOutlineAnswer()) {
							var answer = Memory.getOutlineAnswer();
							Sidebar.subOutlineCount();
							ajaxRecord(answer, function() {
								if (!Memory.hasOutlineAnswer()) {
									form.submit();
								} else {
									var count = Memory.getOutlineAnswerSize();
									form.find("#subFormOutlineCount").text(count);
								}
							});
						} else {
							form.submit();
						}

					}

					$(this).dialog("close");

				},
				"取消" : function() {
					$(this).dialog("close");
				}
			}
		});

	});
</script>

</head>
<body>
	<%@include file="top.jsp"%>
	<div id="submitPanel">
		<form id="subExamForm" action="${ctx}/exam/finishExam.action" method="post">
			<input type="hidden" name="examination.id" value="${examination.id }" /> 
			<span>结束答题，并查看成绩？</span>
		</form>
	</div>
	<div id="sidebar">
		<div class="back">
			<div id="all"></div>
			<div id="load"></div>
			<div id="done"></div>
		</div>

		<div class="front">
			<div class="center">
				<table border="0"> 
					<tr>
						<td class="title">
							<div style="width: 150px;" class="ellipsis">${examination.title}</div>
						</td>
						<td class="score">
						题数：<span id="allCount">${examination.questionCount }</span>&nbsp;&nbsp; 
						正确：<span id="correct" style="color: green; ">${examination.correntCount }</span> &nbsp;&nbsp; 
						错误：<span id="wrong" style="color: red;">${examination.wrongCount }</span> &nbsp;&nbsp; 
							 <span id="offlineNum" style="color: #666;"></span>
						</td>
						<td class="chlang">
						<label id="submitExamButton" style="display: none;" > 
							<a href="javascript:showSubmitDialog()" style="color:orange;">查看成绩</a>
						</label> 
						<label id="loadQuestionBut" > 
							<a href="javascript:loadAllRemainingQuestions()">加载全部题目</a> &nbsp;&nbsp;&nbsp;&nbsp;
							<a href="javascript:loadMore()">加载更多题目</a>
						</label> 
						<a style="margin-left: 10px;" href="javascript:$('#sidebar_menu').toggle(100)">设置</a>
						
						</td>
					</tr>

				</table>
			</div>
		</div>
		
		<div id="sidebar_menu" >
				<div style="width:50%;text-align: left;float: left;height: 10px; margin:3px; font-size: 10px;">设置</div>
				<div style="width:20%;text-align: right;float:right;height: 10px;margin:3px;font-size: 10px;">
					<a onclick=" $('#sidebar_menu').hide(100)">X</a>
				</div>
			<div style="width:100%;  border-top: 1px solid #ccc; clear: both;">
				<ul>
					<li><label><input type="checkbox" id="autoRemove" style="margin-right: 5px;">移除答对题目</label> </li>
					<li><label><input class="language" type="checkbox" onclick="switchLanguage('CN',this)" checked="checked">中文</label> </li>
					<li><label><input class="language" type="checkbox" onclick="switchLanguage('EN',this)"	checked="checked">英文</label></li>
				</ul>
			</div>
		</div>
	</div>
	<div class="width center radius paper">
		<div class="examname">
			<h1>${examination.title}</h1>
		</div>
		<div style=" display: none; " id="chart">
			<div id="chartdiv" align="center"></div>
		</div>
		<div id="context">
			<!-- 试题区域 -->
		</div>

	</div>



	<div id="template" style="display: none;">
		<div id="tempForm">
			<form class="question">
				<input type="hidden" name="answer.questionId" value="{id}" /> <label>[试题编号：{no } 章节：{chapterName} ]</label>
				<ul class="summaryArea">
					<!-- 试题内容区域 -->
				</ul>
				<div align="right">
					<label class="unsure"> <input type="checkbox" style="margin-top: -3px; margin-right: 5px;" />添加至错题库
					</label> <input type="button" class="button gray small hideButton" style="display:none;" onclick="removeQuestion(this,'{id}') " value="移除" /> 
					<input type="button" class="button green small" onclick="submitAnswer(this,'{id}');" value="校对答案" />
					<div class="analysisArea help radius" align="left">
						<!-- 答案解析区域 -->
					</div>
				</div>
			</form>
		</div>

		<div id="tempSummary">
			<li class="{language}">
				<dl class="optionsArea">
					<dt class="title">
						<span class="no">{index}.</span>&nbsp; <span>{summary}</span>
					</dt>

					<!-- 选项区域 -->
				</dl>
			</li>

		</div>

		<div id="tempOption">
			<dd class="option">
				<label> <input type="radio" name="{language}" title="{no}" onclick="syncAnswerSelected(this)" />{no}.&nbsp; <span> {summary} </span>
				</label>
			</dd>
		</div>

		<div id="tempAnswer">
			<span class="answer">答案：{answer}</span> <span class="analysis">{analysis}</span>
		</div>

	</div>
	 
	
	<%@include file="../core/bottom.jsp"%>
</body>
</html>
